import { AIConfig } from './types';

// Cookie工具类
class CookieManager {
  // 设置cookie
  static setCookie(name: string, value: string, days: number = 30): void {
    const expires = new Date();
    expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=Strict`;
  }

  // 获取cookie
  static getCookie(name: string): string | null {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) {
        return decodeURIComponent(c.substring(nameEQ.length, c.length));
      }
    }
    return null;
  }

  // 删除cookie
  static deleteCookie(name: string): void {
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
  }
}

// 配置UI管理器
export class ConfigUI {
  private container: HTMLElement | null = null;
  private isVisible = false;
  private onConfigSaved?: (config: AIConfig) => void;

  constructor() {
    this.loadConfigFromCookie();
  }

  // 从cookie加载配置
  private loadConfigFromCookie(): AIConfig | null {
    try {
      const configStr = CookieManager.getCookie('webcraft_ai_config');
      if (configStr) {
        return JSON.parse(configStr);
      }
    } catch (error) {
      console.warn('Failed to load config from cookie:', error);
    }
    return null;
  }

  // 保存配置到cookie
  private saveConfigToCookie(config: AIConfig): void {
    try {
      // 不保存完整的API密钥，只保存前几位用于验证
      const configToSave = {
        ...config,
        apiKey: config.apiKey.substring(0, 8) + '***'
      };
      CookieManager.setCookie('webcraft_ai_config', JSON.stringify(configToSave), 30);
      
      // API密钥单独保存（加密存储）
      CookieManager.setCookie('webcraft_api_key', this.encryptApiKey(config.apiKey), 30);
    } catch (error) {
      console.warn('Failed to save config to cookie:', error);
    }
  }

  // 简单的API密钥加密（仅用于演示，实际应用需要更安全的方法）
  private encryptApiKey(apiKey: string): string {
    return btoa(apiKey.split('').reverse().join(''));
  }

  // 解密API密钥
  private decryptApiKey(encrypted: string): string {
    try {
      return atob(encrypted).split('').reverse().join('');
    } catch {
      return '';
    }
  }

  // 获取完整配置（包括解密的API密钥）
  getFullConfig(): AIConfig | null {
    const config = this.loadConfigFromCookie();
    if (!config) return null;

    const encryptedKey = CookieManager.getCookie('webcraft_api_key');
    if (encryptedKey) {
      config.apiKey = this.decryptApiKey(encryptedKey);
    }

    return config;
  }

  // 显示配置界面
  show(onConfigSaved?: (config: AIConfig) => void): void {
    if (this.isVisible) return;

    this.onConfigSaved = onConfigSaved;
    this.createUI();
    this.isVisible = true;
  }

  // 隐藏配置界面
  hide(): void {
    if (this.container) {
      this.container.remove();
      this.container = null;
    }
    this.isVisible = false;
  }

  // 创建UI界面
  private createUI(): void {
    // 创建遮罩层
    this.container = document.createElement('div');
    this.container.className = 'chat-config-overlay';
    this.container.innerHTML = `
      <div class="chat-config-modal">
        <div class="chat-config-header">
          <h3>AI聊天配置</h3>
          <button class="chat-config-close">&times;</button>
        </div>
        <div class="chat-config-content">
          <div class="config-section">
            <label>
              <input type="checkbox" id="use-mock-service" />
              使用模拟AI服务（解决CORS问题）
            </label>
            <small>如果遇到跨域问题，可以启用此选项使用本地模拟AI</small>
          </div>
          
          <div class="config-section" id="api-config-section">
            <label for="api-key">API密钥 *</label>
            <input type="password" id="api-key" placeholder="请输入千问API密钥" />
            <small>您的API密钥将安全保存在本地cookie中</small>
          </div>
          
          <div class="config-section">
            <label for="api-url">API地址</label>
            <input type="text" id="api-url" value="https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" />
          </div>
          
          <div class="config-section">
            <label for="model">模型</label>
            <select id="model">
              <option value="qwen-max">qwen-max</option>
              <option value="qwen-plus">qwen-plus</option>
              <option value="qwen-turbo">qwen-turbo</option>
            </select>
          </div>
          
          <div class="config-row">
            <div class="config-section">
              <label for="max-tokens">最大令牌数</label>
              <input type="number" id="max-tokens" value="1000" min="100" max="4000" />
            </div>
            
            <div class="config-section">
              <label for="temperature">温度</label>
              <input type="number" id="temperature" value="0.7" min="0" max="2" step="0.1" />
            </div>
          </div>
          
          <div class="config-section">
            <label for="timeout">超时时间(毫秒)</label>
            <input type="number" id="timeout" value="30000" min="5000" max="60000" step="1000" />
          </div>
          
          <div class="config-status" id="config-status"></div>
        </div>
        
        <div class="chat-config-footer">
          <button class="btn-secondary" id="test-config">测试连接</button>
          <button class="btn-primary" id="save-config">保存配置</button>
        </div>
      </div>
    `;

    // 添加样式
    this.addStyles();

    // 绑定事件
    this.bindEvents();

    // 加载现有配置
    this.loadExistingConfig();

    // 添加到页面
    document.body.appendChild(this.container);
  }

  // 添加样式
  private addStyles(): void {
    if (document.getElementById('chat-config-styles')) return;

    const style = document.createElement('style');
    style.id = 'chat-config-styles';
    style.textContent = `
      .chat-config-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      }

      .chat-config-modal {
        background: #2a2a2a;
        border-radius: 12px;
        width: 500px;
        max-width: 90vw;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        color: #ffffff;
      }

      .chat-config-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 24px;
        border-bottom: 1px solid #404040;
      }

      .chat-config-header h3 {
        margin: 0;
        color: #ffffff;
        font-size: 18px;
      }

      .chat-config-close {
        background: none;
        border: none;
        color: #888;
        font-size: 24px;
        cursor: pointer;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        transition: all 0.2s;
      }

      .chat-config-close:hover {
        background: #404040;
        color: #ffffff;
      }

      .chat-config-content {
        padding: 24px;
      }

      .config-section {
        margin-bottom: 20px;
      }

      .config-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
      }

      .config-section label {
        display: block;
        margin-bottom: 6px;
        color: #cccccc;
        font-weight: 500;
        font-size: 14px;
      }

      .config-section input,
      .config-section select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #555;
        border-radius: 6px;
        background: #1a1a1a;
        color: #ffffff;
        font-size: 14px;
        transition: border-color 0.2s;
        box-sizing: border-box;
      }

      .config-section input:focus,
      .config-section select:focus {
        outline: none;
        border-color: #4CAF50;
        box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
      }

      .config-section small {
        display: block;
        margin-top: 4px;
        color: #888;
        font-size: 12px;
      }

      .config-status {
        padding: 12px;
        border-radius: 6px;
        margin-top: 16px;
        font-size: 14px;
        display: none;
      }

      .config-status.success {
        background: rgba(76, 175, 80, 0.2);
        border: 1px solid #4CAF50;
        color: #4CAF50;
        display: block;
      }

      .config-status.error {
        background: rgba(244, 67, 54, 0.2);
        border: 1px solid #f44336;
        color: #f44336;
        display: block;
      }

      .config-status.info {
        background: rgba(33, 150, 243, 0.2);
        border: 1px solid #2196F3;
        color: #2196F3;
        display: block;
      }

      .chat-config-footer {
        padding: 20px 24px;
        border-top: 1px solid #404040;
        display: flex;
        gap: 12px;
        justify-content: flex-end;
      }

      .btn-primary,
      .btn-secondary {
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
      }

      .btn-primary {
        background: #4CAF50;
        color: white;
      }

      .btn-primary:hover {
        background: #45a049;
      }

      .btn-primary:disabled {
        background: #666;
        cursor: not-allowed;
      }

      .btn-secondary {
        background: #555;
        color: white;
      }

      .btn-secondary:hover {
        background: #666;
      }

      @media (max-width: 600px) {
        .chat-config-modal {
          width: 95vw;
          margin: 20px;
        }
        
        .config-row {
          grid-template-columns: 1fr;
        }
        
        .chat-config-footer {
          flex-direction: column;
        }
      }
    `;

    document.head.appendChild(style);
  }

  // 绑定事件
  private bindEvents(): void {
    if (!this.container) return;

    // 关闭按钮
    const closeBtn = this.container.querySelector('.chat-config-close');
    closeBtn?.addEventListener('click', () => this.hide());

    // 点击遮罩关闭
    this.container.addEventListener('click', (e) => {
      if (e.target === this.container) {
        this.hide();
      }
    });

    // 保存配置
    const saveBtn = this.container.querySelector('#save-config');
    saveBtn?.addEventListener('click', () => this.saveConfig());

    // 测试连接
    const testBtn = this.container.querySelector('#test-config');
    testBtn?.addEventListener('click', () => this.testConnection());

    // 模拟服务复选框
    const mockCheckbox = this.container.querySelector('#use-mock-service') as HTMLInputElement;
    mockCheckbox?.addEventListener('change', () => this.toggleMockService());

    // ESC键关闭
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && this.isVisible) {
        this.hide();
      }
    });
  }

  // 加载现有配置
  private loadExistingConfig(): void {
    if (!this.container) return;

    // 加载模拟服务设置
    const useMock = this.isUsingMockService();
    const mockCheckbox = this.container.querySelector('#use-mock-service') as HTMLInputElement;
    if (mockCheckbox) {
      mockCheckbox.checked = useMock;
      this.toggleMockService();
    }

    // 如果不使用模拟服务，加载API配置
    if (!useMock) {
      const config = this.getFullConfig();
      if (config) {
        const inputs = {
          'api-key': config.apiKey || '',
          'api-url': config.apiUrl || '',
          'model': config.model || 'qwen-max',
          'max-tokens': config.maxTokens?.toString() || '1000',
          'temperature': config.temperature?.toString() || '0.7',
          'timeout': config.timeout?.toString() || '30000'
        };

        Object.entries(inputs).forEach(([id, value]) => {
          const input = this.container!.querySelector(`#${id}`) as HTMLInputElement;
          if (input) {
            input.value = value;
          }
        });
      }
    }
  }

  // 保存配置
  private saveConfig(): void {
    if (!this.container) return;

    const mockCheckbox = this.container.querySelector('#use-mock-service') as HTMLInputElement;
    const useMock = mockCheckbox.checked;

    try {
      // 保存模拟服务设置
      this.setUseMockService(useMock);

      if (useMock) {
        // 使用模拟服务，创建默认配置
        const mockConfig: AIConfig = {
          apiKey: 'mock-key',
          apiUrl: 'mock://localhost',
          model: 'mock-model',
          maxTokens: 1000,
          temperature: 0.7,
          timeout: 10000
        };
        
        this.showStatus('模拟AI服务已启用！', 'success');
        
        if (this.onConfigSaved) {
          this.onConfigSaved(mockConfig);
        }
      } else {
        // 使用真实API服务
        const config = this.getConfigFromForm();
        if (!config) return;

        this.saveConfigToCookie(config);
        this.showStatus('配置已保存！', 'success');
        
        if (this.onConfigSaved) {
          this.onConfigSaved(config);
        }
      }

      setTimeout(() => this.hide(), 1500);
    } catch (error) {
      this.showStatus('保存配置失败：' + (error as Error).message, 'error');
    }
  }

  // 测试连接
  private async testConnection(): Promise<void> {
    if (!this.container) return;

    const config = this.getConfigFromForm();
    if (!config) return;

    const testBtn = this.container.querySelector('#test-config') as HTMLButtonElement;
    const originalText = testBtn.textContent;
    
    testBtn.disabled = true;
    testBtn.textContent = '测试中...';
    this.showStatus('正在测试连接...', 'info');

    try {
      // 简单的连接测试
      const response = await fetch(config.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        body: JSON.stringify({
          model: config.model,
          input: {
            messages: [{ role: 'user', content: 'test' }]
          },
          parameters: { max_tokens: 10 }
        })
      });

      if (response.ok || response.status === 400) {
        // 400也算成功，因为可能是请求格式问题，但认证是通过的
        this.showStatus('连接测试成功！API配置正确。', 'success');
      } else if (response.status === 401) {
        this.showStatus('API密钥无效，请检查密钥是否正确。', 'error');
      } else {
        this.showStatus(`连接失败：${response.status} ${response.statusText}`, 'error');
      }
    } catch (error) {
      this.showStatus('连接测试失败：' + (error as Error).message, 'error');
    } finally {
      testBtn.disabled = false;
      testBtn.textContent = originalText;
    }
  }

  // 从表单获取配置
  private getConfigFromForm(): AIConfig | null {
    if (!this.container) return null;

    const mockCheckbox = this.container.querySelector('#use-mock-service') as HTMLInputElement;
    if (mockCheckbox.checked) {
      // 返回模拟配置
      return {
        apiKey: 'mock-key',
        apiUrl: 'mock://localhost',
        model: 'mock-model',
        maxTokens: 1000,
        temperature: 0.7,
        timeout: 10000
      };
    }

    const getValue = (id: string): string => {
      const input = this.container!.querySelector(`#${id}`) as HTMLInputElement;
      return input?.value?.trim() || '';
    };

    const apiKey = getValue('api-key');
    if (!apiKey) {
      this.showStatus('请输入API密钥', 'error');
      return null;
    }

    const config: AIConfig = {
      apiKey,
      apiUrl: getValue('api-url') || 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
      model: getValue('model') || 'qwen-max',
      maxTokens: parseInt(getValue('max-tokens')) || 1000,
      temperature: parseFloat(getValue('temperature')) || 0.7,
      timeout: parseInt(getValue('timeout')) || 30000
    };

    // 验证配置
    if (config.maxTokens < 100 || config.maxTokens > 4000) {
      this.showStatus('最大令牌数必须在100-4000之间', 'error');
      return null;
    }

    if (config.temperature < 0 || config.temperature > 2) {
      this.showStatus('温度必须在0-2之间', 'error');
      return null;
    }

    return config;
  }

  // 显示状态信息
  private showStatus(message: string, type: 'success' | 'error' | 'info'): void {
    if (!this.container) return;

    const statusEl = this.container.querySelector('#config-status');
    if (statusEl) {
      statusEl.textContent = message;
      statusEl.className = `config-status ${type}`;
    }
  }

  // 清除配置
  clearConfig(): void {
    CookieManager.deleteCookie('webcraft_ai_config');
    CookieManager.deleteCookie('webcraft_api_key');
  }

  // 切换模拟服务
  private toggleMockService(): void {
    if (!this.container) return;

    const mockCheckbox = this.container.querySelector('#use-mock-service') as HTMLInputElement;
    const apiConfigSection = this.container.querySelector('#api-config-section') as HTMLElement;
    const testBtn = this.container.querySelector('#test-config') as HTMLButtonElement;

    if (mockCheckbox.checked) {
      // 启用模拟服务，隐藏API配置
      apiConfigSection.style.display = 'none';
      testBtn.style.display = 'none';
      this.showStatus('已启用模拟AI服务，无需配置API密钥', 'info');
    } else {
      // 禁用模拟服务，显示API配置
      apiConfigSection.style.display = 'block';
      testBtn.style.display = 'inline-block';
      this.showStatus('', 'info');
    }
  }

  // 检查是否使用模拟服务
  isUsingMockService(): boolean {
    const mockConfig = CookieManager.getCookie('webcraft_use_mock');
    return mockConfig === 'true';
  }

  // 设置模拟服务状态
  setUseMockService(useMock: boolean): void {
    CookieManager.setCookie('webcraft_use_mock', useMock.toString(), 30);
  }

  // 检查是否有保存的配置
  hasConfig(): boolean {
    return this.getFullConfig() !== null || this.isUsingMockService();
  }
}

// 导出单例实例
export const configUI = new ConfigUI();